from flask import Flask,request
from flask import render_template,send_from_directory,jsonify
from flask_cors import CORS, cross_origin
import os,sys
import time
# import ssl
ssl_keys = ('secret/server.crt', 'secret/server.key')
app = Flask(__name__,static_folder="static")
app.debug = True
app.json.ensure_ascii = False
ALLOWED_EXTENSIONS = {'pdf', 'PDF',"zip"}
# ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)

password = "123456"
# ctx.load_cert_chain( 'secret/rsa_public_key.pem','secret/rsa_private_key.pem', password=password)
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def CheckFolder(filepath):
	if os.path.exists(filepath):
		return True
	else:
		os.makedirs(filepath)

homePath = os.getcwd()
tmp_path = "{}/tmp".format(homePath)
convert_path = "{}/convert".format(homePath)
assets_path = "{}/assets".format(homePath)

CheckFolder(tmp_path)
CheckFolder(convert_path)


@app.route("/")
def indexView():
	return render_template("index.html")

@app.route('/convert/<filename>/')
def get_image(filename):
    return  send_from_directory(convert_path,filename)

@app.route('/assets/<filename>/')
def GetAssets(filename):
    return  send_from_directory(assets_path,filename)

@app.route("/v1/pdf2doc", methods=['POST'])
@cross_origin(origins='*', methods=['GET', 'POST'])
def PdfToDoc():
	
	from pdf2docx import Converter
	
	reqeust_file = request.files.get("file")
	if reqeust_file == None:
		print(request.files)
		return  {"code":201,"msg":"未获取到文件","data":{}}
	print(reqeust_file.filename)

	if reqeust_file and allowed_file(reqeust_file.filename):
		pass
	else:
		return {"code":202,"msg":"文件不是pdf","data":{}}

	pdf_file = reqeust_file.filename
	tmpName = "{}/{}".format(tmp_path,pdf_file)
	reqeust_file.save(tmpName)

	docx_file = pdf_file.split(".pdf")[0] + ".docx"
	docx_file_path = "{}/{}".format(convert_path, docx_file)
	cv = Converter(tmpName)
	cv.convert(docx_file_path, start=0, end=None)
	cv.close()
	docDict = {"name":docx_file,"url":"/convert/{}".format(docx_file)}
	res_data = {"code":200,"msg":"ok","data":docDict}
	return  jsonify(res_data)

def Run():
	app.run(host ="0.0.0.0",port=8000, ssl_context=ssl_keys)


if __name__ == '__main__':
	Run()